package com.xiyu.service.repository.material.order;

import com.xiyu.service.model.material.info.MaterialCategoryFetcher;
import com.xiyu.service.model.material.info.MaterialInfoFetcher;
import com.xiyu.service.model.material.order.MaterialPurchaseDetailFetcher;
import com.xiyu.service.model.material.order.MaterialPurchaseFetcher;
import com.xiyu.service.vo.material.purchase.PurchasePageQueryInput;
import com.xiyu.service.model.material.order.MaterialPurchase;
import com.xiyu.service.model.material.order.MaterialPurchaseTable;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;
import java.util.Optional;

public interface MaterialPurchaseRepository extends JRepository<MaterialPurchase, Long> {
    MaterialPurchaseTable materialPurchaseTable = MaterialPurchaseTable.$;

    default Page<MaterialPurchase> pageQuery(PurchasePageQueryInput inputVO){
        return sql().createQuery(materialPurchaseTable)
                .whereIf(inputVO.getWarehouseId() != null,
                        materialPurchaseTable.warehouseId().eq(inputVO.getWarehouseId()))
                .whereIf(StringUtils.hasText(inputVO.getPurchaseNo()),
                        () -> materialPurchaseTable.purchaseNo().like(inputVO.getPurchaseNo()))
                .whereIf(inputVO.getStatus() != null,
                        () -> materialPurchaseTable.status().in(inputVO.getStatus()))
                .orderBy(materialPurchaseTable.id().desc())
                .select(materialPurchaseTable)
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

    default Optional<MaterialPurchase> findDetailById(Long id){
        return sql().createQuery(materialPurchaseTable)
                .where(materialPurchaseTable.id().eq(id))
                .select(materialPurchaseTable.fetch(MaterialPurchaseFetcher.$.allTableFields().details(
                        MaterialPurchaseDetailFetcher.$.allTableFields().material(
                                MaterialInfoFetcher.$.allTableFields().category(MaterialCategoryFetcher.$.allTableFields())
                        ))))
                .fetchOptional();
    };

    default void updateStatus(Long id, Integer status){
        sql().createUpdate(materialPurchaseTable)
                .set(materialPurchaseTable.status(), status)
                .where(materialPurchaseTable.id().eq(id))
                .execute();
    }
}